package com.ieasy.module.system.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;
import javax.transaction.Transactional;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Service;

import com.ieasy.basic.dao.IBaseDao;
import com.ieasy.basic.exception.ServiceException;
import com.ieasy.basic.model.DataGrid;
import com.ieasy.basic.model.Msg;
import com.ieasy.basic.model.Pager;
import com.ieasy.basic.model.SystemContext;
import com.ieasy.basic.util.BeanUtils;
import com.ieasy.basic.util.StringUtil;
import com.ieasy.basic.util.dbutil.IDBUtilsHelper;
import com.ieasy.module.system.entity.Intellectual;
import com.ieasy.module.system.entity.RoleEntity;
import com.ieasy.module.system.web.form.IntellEctualForm;
import com.ieasy.module.system.web.form.RoleForm;

@Service @Transactional
public class IntellectualService implements IIntellectualService {
	
	private Logger logger = Logger.getLogger(getClass()) ;

	@Inject
	private IBaseDao<Intellectual> basedaoIntell ;
	
	@Inject
	private IBaseDao<RoleEntity> basedaoRole ;
	
	@Inject
	private IDBUtilsHelper dbutil ;

	@Override
	public Msg add(IntellEctualForm form) {
		System.out.println(form.getContent());
		try {
			Intellectual entity = new Intellectual() ;
			BeanUtils.copyNotNullProperties(form, entity) ;
			
			Set<RoleEntity> roles = new HashSet<RoleEntity>() ;
			
			if(null != form.getRole_ids() && !"".equals(form.getRole_ids())) {
				String[] split = form.getRole_ids().split(",") ;
				for (String role_id : split) {
					roles.add(this.basedaoRole.load(RoleEntity.class, role_id)) ;
				}
			}
			entity.setRoles(roles) ;
			this.basedaoIntell.add(entity);
			
			return new Msg(true, "添加成功！");
		} catch (BeansException e) {
			logger.error("添加失败===>异常信息：", e) ;
			return new Msg(false, "添加失败！") ;
		}
	}

	@Override
	public Msg delete(IntellEctualForm form) {
		try {
			if(null != form.getIds() && !"".equals(form.getIds())) {
				String[] ids = form.getIds().split(",") ;
				for (String id : ids) {
					this.basedaoIntell.delete(Intellectual.class, Integer.parseInt(id)) ;
				}
			}
			return new Msg(true, "删除成功！") ;
		} catch (Exception e) {
			logger.error("根据ID["+form.getIds()+"]删除用户信息失败===>异常信息：", e) ;
			return new Msg(false, "删除失败！") ;
		}
	}

	@Override
	public Msg update(IntellEctualForm form) {
		try {
			Intellectual entity = this.basedaoIntell.load(Intellectual.class, form.getId()) ;
			BeanUtils.copyNotNullProperties(form, entity) ;
			
			if(null != form.getRole_ids() && !"".equals(form.getRole_ids())) {
				Set<RoleEntity> roles = new HashSet<RoleEntity>() ;
				String[] split = form.getRole_ids().split(",") ;
				for (String role_id : split) {
					roles.add(this.basedaoRole.load(RoleEntity.class, role_id)) ;
				}
				entity.setRoles(roles) ;
			} else {
				entity.setRoles(null) ;
			}
			

			this.basedaoIntell.update(entity) ;
			return new Msg(true, "修改成功！");
		} catch (BeansException e) {
			logger.error("修改失败===>异常信息：", e) ;
			return new Msg(false, "修改失败！") ;
		}
	}

	@Override
	public IntellEctualForm get(IntellEctualForm form) {
		try {
			String sql = "select " +
					 	 "u.id, u.title, u.type, u.content, u.created " +
					 	 "from ieasy_common_intellectual u " +
					 	 "where u.id='"+form.getId()+"'";
			
			form = (IntellEctualForm)this.basedaoIntell.queryObjectSQL(sql, IntellEctualForm.class, false) ;
			
			//获取角色
			List<IntellEctualForm> roles = this.basedaoRole.listSQL("select t.role_id, t.intell_id id from ieasy_common_intell_roles t WHERE t.intell_id=?", new Object[]{form.getId()}, IntellEctualForm.class, false) ;
			if(null != roles) {
				StringBuffer s1 = new StringBuffer() ;
				StringBuffer s2 = new StringBuffer() ;
				for (IntellEctualForm r : roles) {
					s1.append(r.getRole_id()+",");
					s2.append(r.getRole_name()+",");
				}
				form.setRole_ids((s1.length()>0?s1.deleteCharAt(s1.length()-1).toString():"")) ;
				form.setRole_names((s2.length()>0?s2.deleteCharAt(s2.length()-1).toString():"")) ;
			}
			
			return form ;
		} catch (Exception e) {
			e.printStackTrace() ;
			logger.error("加载失败===>异常信息：", e) ;
			throw new ServiceException("加载异常：", e) ;
		}
	}

	@Override
	public DataGrid datagridByRoleView(IntellEctualForm form) {
		if(null != form.getSort()) {
			String[] intellSorts = new String[]{"id", "type", "created"};
			if(StringUtil.arrayToString(intellSorts).contains(form.getSort())) {
				//SystemContext.setSort("ii."+form.getSort()) ; SystemContext.setOrder(form.getOrder()) ;
			}
		}
		
		try {
			DataGrid dg = new DataGrid() ;
			List<IntellEctualForm> forms = new ArrayList<IntellEctualForm>() ;
			
			Map<String, Object> alias1 = new HashMap<String, Object>();
			//form.setRole_ids("402884834a034090014a0340eb8d0178") ;
			String role_ids = form.getRole_ids() ;
			alias1.put("role_ids", (null!=role_ids&&!"".equals(role_ids.trim())?role_ids.split(","):"")) ;
			String sql_roles = "select ir.role_id, ir.intell_id id from ieasy_common_intell_roles ir where ir.role_id in(:role_ids)" ;
			List<IntellEctualForm> listSQL1 = this.basedaoRole.listSQL(sql_roles, alias1, IntellEctualForm.class, false) ;
			Map<Integer, Object> intell_ids = new HashMap<Integer, Object>() ;
			for (IntellEctualForm i : listSQL1) {
				intell_ids.put(i.getId(), i.getRole_id()) ;
			}
			
			if(!intell_ids.isEmpty()) {
				Map<String, Object> alias2 = new HashMap<String, Object>();
				alias2.put("intell_ids", intell_ids.keySet()) ;
				String sql_intell = "select ii.id, ii.type, ii.title, ii.created from ieasy_common_intellectual ii where ii.id in(:intell_ids)" ;
				Pager<IntellEctualForm> pager = this.basedaoIntell.findSQL(sql_intell, alias2, IntellEctualForm.class, false) ;
				if (null != pager && !pager.getDataRows().isEmpty()) {
					for(IntellEctualForm pf : pager.getDataRows()) {
						//获取角色
						List<RoleForm> roles = this.basedaoRole.listSQL("select r.name from ieasy_common_intell_roles t LEFT JOIN ieasy_sys_role r on(r.id=t.role_id) WHERE t.intell_id=?", new Object[]{pf.getId()}, RoleForm.class, false) ;
						if(null != roles) {
							StringBuffer s = new StringBuffer() ;
							for (RoleForm r : roles) {
								s.append(r.getName()+",");
							}
							pf.setRole_names((s.length()>0?s.deleteCharAt(s.length()-1).toString():"")) ;
						}
						
						forms.add(pf) ;
					}
				}
				
				dg.setTotal(pager.getTotal());
				dg.setRows(forms);
			}
 			
			return dg;
		} catch (Exception e) {
			e.printStackTrace() ;
			logger.error("加载失败===>异常信息：", e) ;
			throw new ServiceException("加载异常：", e) ;
		}
	}
	
	@Override
	public DataGrid datagrid(IntellEctualForm form) {
		if(null != form.getSort()) {
			String[] intellSorts = new String[]{"id", "type", "created"};
			if(StringUtil.arrayToString(intellSorts).contains(form.getSort())) {
				SystemContext.setSort("u."+form.getSort()) ; SystemContext.setOrder(form.getOrder()) ;
			}
		}
		
		try {
			List<IntellEctualForm> forms = new ArrayList<IntellEctualForm>() ;
			Pager<IntellEctualForm> pager = this.find(form) ;
			if (null != pager && !pager.getDataRows().isEmpty()) {
				for(IntellEctualForm pf : pager.getDataRows()) {
					//获取角色
					List<RoleForm> roles = this.basedaoRole.listSQL("select r.name from ieasy_common_intell_roles t LEFT JOIN ieasy_sys_role r on(r.id=t.role_id) WHERE t.intell_id=?", new Object[]{pf.getId()}, RoleForm.class, false) ;
					if(null != roles) {
						StringBuffer s = new StringBuffer() ;
						for (RoleForm r : roles) {
							s.append(r.getName()+",");
						}
						pf.setRole_names((s.length()>0?s.deleteCharAt(s.length()-1).toString():"")) ;
					}
					
					forms.add(pf) ;
				}
			}
			DataGrid dg = new DataGrid() ;
			dg.setTotal(pager.getTotal());
			dg.setRows(forms);
			return dg;
		} catch (Exception e) {
			e.printStackTrace() ;
			logger.error("加载失败===>异常信息：", e) ;
			throw new ServiceException("加载异常：", e) ;
		}
	}
	
	
	private Pager<IntellEctualForm> find(IntellEctualForm form) {
		Map<String, Object> alias = new HashMap<String, Object>();
		String sql = "select " +
					 "u.id, u.type, u.title, u.created " +
				 	 "from ieasy_common_intellectual u " +
				 	 "where 1=1 ";
		sql = addWhere(sql, form, alias) ;
		return this.basedaoIntell.findSQL(sql, alias, IntellEctualForm.class, false) ;
	}
	
	private String addWhere(String sql, IntellEctualForm form, Map<String, Object> params) {
		if (null != form) {
			if (form.getType() != null && !"".equals(form.getType().trim())) {
				sql += " and u.type like :type";
				params.put("type", "%%" + form.getType() + "%%");
			}
			if (form.getTitle() != null && !"".equals(form.getTitle().trim())) {
				sql += " and u.title like :title";
				params.put("title", "%%" + form.getTitle() + "%%");
			}
		}
		return sql;
	}

}
